//
//  AnyObserverExample.swift
//  rxExample
//
//  Created by 刘山 on 2021/11/4.
//

import Foundation
import UIKit
import RxSwift
import RxCocoa
import SnapKit

@objc(AnyObserverExample)
public class AnyObserverExample: UIViewController {
    let disposeBag = DisposeBag()
    
    public override func viewDidLoad() {
        self.view.backgroundColor = UIColor.white
        //observer_demo()
    }
    
    func observer_demo() {
        URLSession.shared.rx.data(request: URLRequest(url: URL(string: "")!))
            .subscribe { data in
            } onError: { error in
            } onCompleted: {
                print("Completed!")
            }.disposed(by: disposeBag)
    }
    
    func any_observer_demo() {
        let obs: AnyObserver<Data> = AnyObserver { (event) in
            switch event {
            case .next(let data):
                print("Data Task Success with count: \(data.count)")
            case .error(let error):
                print("Data Task Fail: \(error)")
            default:
                break
            }
        }
        
        URLSession.shared.rx.data(request: URLRequest(url: URL(string: "")!))
            .subscribe(obs)
            .disposed(by: disposeBag)
    }
    
    let usernameOutlet = UITextField()
    let usernameValidOutlet = UILabel()
    func bind_demo() {
        let usernameValid = usernameOutlet.rx.text.orEmpty.map { $0.count >= 5 }.share(replay: 1, scope: .forever)
        
        usernameValid.bind(to: usernameValidOutlet.rx.isHidden).disposed(by: disposeBag)

        /// 等价于
        let obs: AnyObserver<Bool> = AnyObserver { [weak self] (event) in
            switch event {
            case .next(let isHidden):
                self?.usernameValidOutlet.isEnabled = isHidden
            default:
                break
            }
        }
        usernameValid.bind(to: obs).disposed(by: disposeBag)
        
        /// 等价于
        let bind: Binder<Bool> = Binder(usernameValidOutlet) { (view, isHidden) in
            view.isEnabled = isHidden
        }
        usernameValid.bind(to: bind).disposed(by: disposeBag)
    }
}
extension Reactive where Base: UIView {
    public var isHidden: Binder<Bool> {
        return Binder(self.base) { (view, isHidden) in
            view.isHidden = isHidden
        }
    }
}

